
Page({
  data: {
    items: [],
    filteredItems: [], // 用于存储当前分类下的习惯
    startX: 0,
    startY: 0,
    isshow: true,
    userId: '',
    userInfo: null,
    showOptionsModal: false, // 控制弹窗显示隐藏
    selectedHabitIndex: -1, // 记录当前长按的习惯索引
    actionSheetAnimation: false, // 控制弹窗动画
    optionsModalPosition: { top: 0, left: 0, width: 0 }, // 存储弹窗位置和宽度
    screenWidth: 0, // 存储屏幕宽度
    importantOptionText: '', // 新增重要习惯选项文本
    currentCategory: 'all', // 当前选中的分类
    categories: [
      { id: 'morning', name: '起床' },
      { id: 'morning_routine', name: '晨间' },
      { id: 'noon', name: '中午' },
      { id: 'afternoon', name: '午间' },
      { id: 'evening', name: '晚间' },
      { id: 'before_sleep', name: '睡前' },
      { id: 'all_day', name: '全天' }
    ],
    categorizedHabits: {},
    // 定义分类映射关系 (英文ID到中文名称)
    categoryMapping: {
      'morning': '起床',
      'morning_routine': '晨间',
      'noon': '中午',
      'afternoon': '午间',
      'evening': '晚间',
      'before_sleep': '睡前',
      'all_day': '全天',
      'important': '重要习惯' // 添加重要习惯分类
    },
    // 定义反向分类映射关系 (中文名称到英文ID)
    reverseCategoryMapping: {},
    categoryItemCounts: { // 用于存储每个分类的习惯数量
      all: 0,
      morning: 0,
      morning_routine: 0,
      noon: 0,
      afternoon: 0,
      evening: 0,
      before_sleep: 0,
      all_day: 0,
      important: 0,
      other: 0 // 其他分类的计数
    }
  },

  onLoad: function () {
    // 获取屏幕宽度
    const res = wx.getSystemInfoSync();
    this.setData({
      screenWidth: res.screenWidth
    });

    // 初始化反向分类映射
    const reverseMapping = {};
    for (const key in this.data.categoryMapping) {
      reverseMapping[this.data.categoryMapping[key]] = key;
    }
    this.setData({
      reverseCategoryMapping: reverseMapping
    });
    const userId = wx.getStorageSync('userId');
    const userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userId: userId,
      userInfo: userInfo
    });

    // 如果有用户ID，加载该用户的习惯列表
    if (userId) {
      this.loadHabits(userId);
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
    }
  },

  // 加载用户习惯列表
  loadHabits(userId) {
    wx.request({
      url: 'http://127.0.0.1:3001/getUserHabit',
      method: 'GET',
      data: {
        userId: userId
      },
      success: (res) => {
        if (res.data) {
          console.log('Raw habits data from backend:', res.data);
          const habits = res.data.map(habit => {
            console.log('Processing habit:', {
              habit_id: habit.habit_id,
              habit_name: habit.habit_name,
              frequency_type: habit.habit_frequency_type,
              frequency_value: habit.habit_frequency_value,
              frequency_days: habit.habit_frequency_days
            });
            return {
              ...habit,
              isFinished: habit.is_finished === 1,
              isTouchMove: false,
              displayFrequency: this.getDisplayFrequency(habit)
            };
          });

          console.log('Processed habits with displayFrequency:', habits);

          const newCategorizedHabits = {};

          // 初始化所有分类为空数组
          for (const categoryId in this.data.categoryMapping) {
            newCategorizedHabits[categoryId] = [];
          }
          // 添加一个默认的"其他"分类，用于没有匹配情景的习惯
          newCategorizedHabits['other'] = []; 

          habits.forEach(habit => {
            let addedToCategory = false;
            // 处理重要习惯
            if (habit.is_important === 1) {
              newCategorizedHabits['important'].push(habit);
              addedToCategory = true;
            }
            
            // 处理打卡情景
            if (habit.punch_in_scenarios) {
              const scenarios = habit.punch_in_scenarios.split(',').map(s => s.trim());
              scenarios.forEach(scenarioName => {
                const categoryId = this.data.reverseCategoryMapping[scenarioName];
                if (categoryId && newCategorizedHabits[categoryId]) {
                  newCategorizedHabits[categoryId].push(habit);
                  addedToCategory = true;
                }
              });
            }
            // 如果习惯没有被添加到任何特定情景分类，则将其添加到"其他"分类
            if (!addedToCategory) {
              newCategorizedHabits['other'].push(habit);
            }
          });

          // 计算每个分类的习惯数量
          const updatedCategoryCounts = { ...this.data.categoryItemCounts }; // 复制一份，避免直接修改 state
          for (const categoryId in newCategorizedHabits) {
            updatedCategoryCounts[categoryId] = newCategorizedHabits[categoryId].length;
          }
          updatedCategoryCounts.all = habits.length; // "全部"分类是所有习惯的总数

          // 更新 categories 数组，使其包含每个分类的 count 属性
          const updatedCategories = this.data.categories.map(cat => ({
            ...cat,
            count: updatedCategoryCounts[cat.id] || 0 // 确保 count 存在
          }));

          this.setData({
            items: habits,
            categorizedHabits: newCategorizedHabits,
            categoryItemCounts: updatedCategoryCounts, // 更新计数
            categories: updatedCategories // 更新带有计数的分类数组
          });
          this.filterHabits(); // 初始过滤所有习惯
          console.log('items', habits);
          console.log('categorizedHabits', newCategorizedHabits);
          console.log('Filtered items after loadHabits:', this.data.filteredItems);
          console.log('Updated Category Counts:', updatedCategoryCounts);
        }
      },
      fail: () => {
        wx.showToast({
          title: '加载习惯列表失败',
          icon: 'none'
        });
      }
    });
  },

  // 获取主要打卡频率描述
  getDisplayFrequency(habit) {
    const type = parseInt(habit.habit_frequency_type);
    const value = parseInt(habit.habit_frequency_value) || 0;
    const days = habit.habit_frequency_days || '';

    console.log('Display frequency calculation:', {
      type,
      value,
      days,
      habit_frequency_value: habit.habit_frequency_value
    });

    if (type === 1) {
      // 固定频率，显示具体的周几
      if (days && days.trim() !== '') {
        const dayNames = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        const selectedDays = String(days).split(',');
        
        // 如果选择了所有天，显示"每天"
        if (selectedDays.length === 7) {
          return '每天';
        }
        
        // 否则显示具体选择的周几
        const result = selectedDays
          .map(day => {
            const dayIndex = parseInt(day) - 1;
            return dayNames[dayIndex];
          })
          .join('、');
        
        return result;
      } else {
        return '每天';
      }
    } else if (type === 2) {
      // 每周频率
      if (value === 7) {
        return '每天';
      } else if (value > 0) {
        return `每周${value}天`;
      } else {
        return '每周';
      }
    } else if (type === 3) {
      // 每月频率
      if (value === 31) {
        return '每天';
      } else if (value > 0) {
        return `每月${value}天`;
      } else {
        return '每月';
      }
    } else {
      return '每天';
    }
  },

  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    const newItems = this.data.items.map(v => ({ ...v, isTouchMove: false }));

    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      items: newItems // 更新 items 确保所有 isTouchMove 为 false
    }, () => {
      console.log('touchstart - items updated:', this.data.items.map(i => ({ habit_id: i.habit_id, isTouchMove: i.isTouchMove })));
      this.filterHabits(); // 重新过滤以更新 filteredItems，确保在 items 更新后执行
    });
  },

  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });

    // 创建一个新的数组来更新 items，确保 setData 触发渲染
    const updatedItems = this.data.items.map((v, i) => {
      let newItem = { ...v, isTouchMove: false }; // 创建新对象并默认设置为 false

      if (i == index) {
        if (Math.abs(angle) > 30) { // 滑动角度过大，不触发滑动
          newItem.isTouchMove = false;
        } else if (touchMoveX <= startX) { // 左滑
          newItem.isTouchMove = true;
        } else { // 右滑
          newItem.isTouchMove = false;
        }
      }
      return newItem;
    });

    //更新数据 
    that.setData({
      items: updatedItems
    }, () => {
      console.log('touchmove - items updated:', this.data.items.map(i => ({ habit_id: i.habit_id, isTouchMove: i.isTouchMove })));
      this.filterHabits(); // 重新过滤以更新 filteredItems，确保在 items 更新后执行
    });
  },

  /**
  
  * 计算滑动角度
  
  * @param {Object} start 起点坐标
  
  * @param {Object} end 终点坐标
  
  */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y;
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  //删除事件 
  del: function (e) {
    const index = e.currentTarget.dataset.index;
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个习惯吗？这也会删除相关的打卡记录。',
      success: (res) => {
        if (res.confirm) {
          var Id = this.data.items[index].habit_id;
          console.log('Deleting Habit Id:' + Id);
    // 从数据库中删除习惯和相关的日志
    wx.request({
      url: 'http://127.0.0.1:3001/deleteHabit',
      method: 'POST',
      data: {
        habitId: Id,
        userId: this.data.userId
      },
      success: (res) => {
        if (res.data.success) {
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
                // 从本地数组中删除
                 const newItems = this.data.items.filter((_, i) => i !== index);
          this.setData({
                  items: newItems
          });
        } else {
          wx.showToast({
                  title: res.data.message || '删除失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '删除失败',
          icon: 'none'
        });
            },
             complete: () => {
                this.hideOptionsModal(); // 隐藏弹窗
            }
          });
        } else {
           this.hideOptionsModal(); // 用户取消删除也隐藏弹窗
        }
      }
    });
  },

  //结束事件
  finish: function (e) {
    const index = e.currentTarget.dataset.index;
    const habitId = this.data.items[index].habit_id;
    const userId = this.data.userId;

    console.log(`标记习惯结束: habitId=${habitId}, userId=${userId}`);

    // 调用后端接口更新习惯状态
    wx.request({
      url: 'http://127.0.0.1:3001/updateHabitStatus',
      method: 'POST',
      data: {
        userId: userId,
        habitId: habitId,
        is_finished: 1 // 将 is_finished 设置为 1 (true)
      },
      success: (res) => {
        console.log('更新习惯状态成功:', res.data);
        if (res.data.success) {
          wx.showToast({
            title: '习惯已结束',
            icon: 'success'
          });
          // 重新加载未结束的习惯列表
          this.loadHabits(userId);
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('更新习惯状态失败:', err);
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        });
      }
    });
  },

  edit: function (e) {
    const index = e.currentTarget.dataset.index;
    wx.navigateTo({
      url: '../habit_content/habit_content?Id=' + this.data.items[index].id,
    });
    getApp().globalData.page_type = 2;
    getApp().globalData.edit = true;
    this.hideOptionsModal(); // 隐藏弹窗
  },

  goAdd: function () {
    wx.navigateTo({
      url: '../../pages/habits_add/habits_add',
    });
    getApp().globalData.page_type = 2;
  },

  show: function () {
    this.setData({
      isshow: !this.data.isshow
    });
  },

  continueHabit: function (e) {
    const index = e.currentTarget.dataset.index;
    const habit = this.data.items[index];
    // 只有已结束的习惯才能执行继续开始操作
    if (!habit.isFinished) {
      console.log('该习惯未结束，无需继续开始操作');
      return;
    }

    // 检查习惯的结束时间是否晚于当前时间
    const finishDate = new Date(habit.habit_finishedTime);
    const now = new Date();

    // 检查 finishDate 是否是有效的日期对象
    if (isNaN(finishDate.getTime())) {
      console.error('无效的习惯结束时间:', habit.habit_finishedTime);
      wx.showToast({
        title: '获取习惯结束时间失败',
        icon: 'none'
      });
      return;
    }

    if (finishDate > now) {
      console.log('结束时间未到，可以继续开始');

      const habitId = habit.habit_id;
      const userId = this.data.userId;

      console.log(`继续开始习惯: habitId=${habitId}, userId=${userId}`);

      // 调用后端接口更新习惯状态为未结束
      wx.request({
        url: 'http://127.0.0.1:3001/updateHabitStatus',
        method: 'POST',
        data: {
          userId: userId,
          habitId: habitId,
          is_finished: 0 // 将 is_finished 设置为 0 (false)
          // 可以选择清空 finish_date 或更新为未来的某个默认值
        },
        success: (res) => {
          console.log('更新习惯状态成功:', res.data);
          if (res.data.success) {
            wx.showToast({
              title: '习惯已恢复',
              icon: 'success'
            });
            // 更新本地数据并刷新页面显示
            const updatedItems = this.data.items.map((item, i) => {
              if (i === index) {
                return {
                  ...item,
                  is_finished: 0,
                  isFinished: false
                };
              }
              return item;
            });
            this.setData({
              items: updatedItems
            });
          } else {
            wx.showToast({
              title: res.data.message || '操作失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('更新习惯状态失败:', err);
          wx.showToast({
            title: '操作失败',
            icon: 'none'
          });
        }
      });
    } else {
      // 结束时间已到或已过
      console.log('结束时间已到或已过，不能继续开始');
      wx.showToast({
        title: '设定的继续时间已过',
        icon: 'none'
      });
    }
  },

  goDetail: function(e) {
    const habitId = e.currentTarget.dataset.habitid;
    const userId = this.data.userId;
    wx.navigateTo({
      url: `/pages/stat_detail/stat_detail?habit_id=${habitId}&user_id=${userId}`
    });
  },
  // 长按三个点显示选项弹窗
  showHabitOptions: function(e) {
    console.log('Long press triggered. Showing options modal.');
    const index = e.currentTarget.dataset.index;

    // 获取点击元素的位置信息
    const query = wx.createSelectorQuery();
    query.select('.options-circle').boundingClientRect(rect => {
      if (rect) {
        // 弹窗宽度是屏幕宽度的2/3
        const modalWidth = this.data.screenWidth * (2/3);

        // 计算弹窗出现的位置，使其右侧距离屏幕右边缘有一个小的间隔
        const screenRightMargin = 10; // 距离屏幕右边缘10px
        const left = this.data.screenWidth - modalWidth - screenRightMargin;

        // 计算弹窗的top位置，使其顶部在图标的下方，留一个小的间隔
        const verticalMargin = 5; // 图标下方间隔5px
        let top = rect.top + rect.height + verticalMargin; 
        
        // 简单的边界检查，确保不会超出屏幕顶部
        if(top < 0) top = 0;

        // 根据选中习惯的is_important状态设置选项文本
        const selectedHabit = this.data.items[index];
        const optionText = selectedHabit.is_important === 1 ? '取消重要习惯' : '设为重要习惯';

        this.setData({
          selectedHabitIndex: index,
          optionsModalPosition: { top: top, left: left, width: modalWidth }, // 存储位置和宽度
          showOptionsModal: true, // 先显示元素
          importantOptionText: optionText // 设置重要习惯选项文本
        }, () => {
          // 在元素渲染后，再触发动画
          setTimeout(() => {
             this.setData({
               actionSheetAnimation: true
             });
             console.log('actionSheetAnimation is now:', this.data.actionSheetAnimation);
          }, 50); // 稍微延迟确保元素已渲染
        });
      }
    }).exec();

    console.log('showOptionsModal is now:', this.data.showOptionsModal);
  },

  // 隐藏选项弹窗
  hideOptionsModal: function() {
    console.log('Hiding options modal.');
    this.setData({
      actionSheetAnimation: false // 先触发退出动画
    }, () => {
       // 在动画完成后隐藏元素
       setTimeout(() => {
         this.setData({
           showOptionsModal: false,
           selectedHabitIndex: -1,
           optionsModalPosition: { top: 0, left: 0, width: 0 } // Reset position and width
         });
         console.log('showOptionsModal is now:', this.data.showOptionsModal);
       }, 300); // 延迟时间与CSS动画时长一致
    });
     console.log('actionSheetAnimation is now:', this.data.actionSheetAnimation);
  },

  // 弹窗选项处理函数
  editHabit: function() {
    // 调用现有的编辑函数
    this.edit({ currentTarget: { dataset: { index: this.data.selectedHabitIndex } } });
  },

  startFocus: function() {
    console.log('开始专注 selected habit index:', this.data.selectedHabitIndex);
    // TODO: Implement start focus logic
    wx.showToast({
        title: '开始专注功能待实现',
        icon: 'none'
    });
    this.hideOptionsModal();
  },

  setImportant: function() {
    const index = this.data.selectedHabitIndex;
    if (index === -1) return;

    const habitId = this.data.items[index].habit_id;
    const userId = this.data.userId;
    const isCurrentlyImportant = this.data.items[index].is_important === 1;

    console.log(`Setting habit important status: habitId=${habitId}, userId=${userId}, is_important=${isCurrentlyImportant}`);

    wx.request({
      url: 'http://127.0.0.1:3001/updateHabitImportant',
      method: 'POST',
      data: {
        userId: userId,
        habitId: habitId,
        is_important: isCurrentlyImportant ? 0 : 1
      },
      success: (res) => {
        if (res.data.success) {
          // Update local data
          const updatedItems = this.data.items.map((item, i) => {
            if (i === index) {
              return {
                ...item,
                is_important: isCurrentlyImportant ? 0 : 1
              };
            }
            return item;
          });
          
          this.setData({
            items: updatedItems,
            importantOptionText: isCurrentlyImportant ? '设为重要习惯' : '取消重要习惯' // 更新选项文本
          });

          this.filterHabits(); // 调用 filterHabits 来更新 filteredItems

          wx.showToast({
            title: isCurrentlyImportant ? '已取消重要习惯' : '已设为重要习惯',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('Update habit important status failed:', err);
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        });
      },
      complete: () => {
        this.hideOptionsModal();
      }
    });
  },

  setReminder: function() {
     console.log('设置提醒 selected habit index:', this.data.selectedHabitIndex);
    // TODO: Implement set reminder logic
     wx.showToast({
        title: '设置提醒功能待实现',
        icon: 'none'
    });
    this.hideOptionsModal();
  },

  deleteHabit: function() {
    // 调用现有的删除函数
    this.del({ currentTarget: { dataset: { index: this.data.selectedHabitIndex } } });
  },

  // 归档习惯
  archiveHabit: function() {
    const index = this.data.selectedHabitIndex;
    if (index === -1) return; // Should not happen if opened correctly

    const habitId = this.data.items[index].habit_id;
    const userId = this.data.userId;

    console.log(`Archiving Habit: habitId=${habitId}, userId=${userId}`);

    // TODO: Implement backend call to archive habit
    wx.request({
      url: 'http://127.0.0.1:3001/archiveHabit', // Assuming backend endpoint
      method: 'POST',
      data: {
        userId: userId,
        habitId: habitId,
        is_archived: 1 // Assuming archiving means setting a flag
      },
      success: (res) => {
        console.log('Archive habit success:', res.data);
        if (res.data.success) {
          wx.showToast({
            title: '习惯已归档',
            icon: 'success'
          });
          // 从本地列表中移除已归档的习惯
          const newItems = this.data.items.filter((_, i) => i !== index);
          this.setData({
            items: newItems
          });
        } else {
          wx.showToast({
            title: res.data.message || '归档失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('Archive habit failed:', err);
        wx.showToast({
          title: '归档失败',
          icon: 'none'
        });
      },
      complete: () => {
        this.hideOptionsModal(); // Hide modal after request completes
      }
    });
  },

  // 切换分类
  switchCategory: function(e) {
    const category = e.currentTarget.dataset.category;
    this.setData({
      currentCategory: category
    });
    this.filterHabits();
  },

  // 根据当前分类筛选习惯
  filterHabits: function() {
    const { items, currentCategory, categorizedHabits } = this.data;
    let filteredItems = [];

    if (currentCategory === 'all') {
      // 如果是"全部"，则直接使用主 habits 数组，它保存了最新的 isTouchMove 状态
      filteredItems = items;
    } else if (categorizedHabits[currentCategory]) {
      // 如果选择了特定分类，则显示该分类下的习惯
      // 确保从 categorizedHabits 中获取的习惯带有 isTouchMove 状态，通过从 items 中查找对应项
      filteredItems = categorizedHabits[currentCategory].map(habit => items.find(item => item.habit_id === habit.habit_id) || habit);
    } else if (currentCategory === 'other' && categorizedHabits['other']) {
      // 处理"其他"分类
      filteredItems = categorizedHabits['other'].map(habit => items.find(item => item.habit_id === habit.habit_id) || habit);
    }

    this.setData({
      filteredItems: filteredItems
    });
  },

  // 长按显示选项弹窗
  handleLongPress: function (e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      selectedHabitIndex: index
    });

    // 获取长按习惯的当前重要状态
    const isCurrentlyImportant = this.data.items[this.data.selectedHabitIndex].is_important;
    // 根据当前重要状态设置选项文本
    this.setData({
      importantOptionText: isCurrentlyImportant === 1 ? '取消重要' : '设为重要'
    });

    // 计算弹窗位置 (这里只是示例，你需要根据实际布局调整)
    // 假设你希望弹窗出现在长按的习惯卡片附近
    const query = wx.createSelectorQuery();
    query.select(`.habit-card-${this.data.selectedHabitIndex}`).boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec((res) => {
      if (res[0]) {
        const cardRect = res[0];
        const scrollTop = res[1].scrollTop;
        const top = cardRect.top + scrollTop + cardRect.height / 2; // 弹窗中心与卡片中心对齐
        const left = cardRect.left + cardRect.width / 2;

        this.setData({
          showOptionsModal: true,
          actionSheetAnimation: true,
          optionsModalPosition: {
            top: top,
            left: left,
            width: cardRect.width // 弹窗宽度与卡片相同
          }
        });
      }
    });
  },

  // 点击弹窗外部关闭弹窗
  tapOutsideOptionsModal: function () {
    this.setData({
      showOptionsModal: false,
      actionSheetAnimation: false,
      selectedHabitIndex: -1 // 重置选中索引
    });
  },

  // 点击选项按钮，这里只处理重要习惯的设置
  handleOptionClick: function (e) {
    const optionType = e.currentTarget.dataset.type;
    const habit = this.data.items[this.data.selectedHabitIndex];

    if (optionType === 'important') {
      // 切换重要状态
      const newImportantStatus = habit.is_important === 1 ? 0 : 1;
      console.log(`Setting habit important status: habitId=${habit.habit_id}, userId=${this.data.userId}, is_important=${newImportantStatus}`);

      wx.request({
        url: 'http://127.0.0.1:3001/updateHabitImportant',
        method: 'POST',
        data: {
          habitId: habit.habit_id,
          userId: this.data.userId,
          is_important: newImportantStatus // 修改参数名
        },
        success: (res) => {
          if (res.data.success) {
            wx.showToast({
              title: '设置成功',
              icon: 'success'
            });
            // 更新本地数据
            const updatedItems = this.data.items.map((item, index) => {
              if (index === this.data.selectedHabitIndex) {
                return { ...item,
                  is_important: newImportantStatus
                };
              }
              return item;
            });
            this.setData({
              items: updatedItems,
              filteredItems: this.filterHabits(updatedItems, this.data.currentCategory) // 重新过滤以更新显示
            });
            this.tapOutsideOptionsModal(); // 关闭弹窗
          } else {
            wx.showToast({
              title: res.data.message || '设置失败',
              icon: 'none'
            });
            this.tapOutsideOptionsModal(); // 关闭弹窗
          }
        },
        fail: (err) => {
          console.error('更新习惯重要状态失败:', err);
          wx.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
          this.tapOutsideOptionsModal(); // 关闭弹窗
        }
      });
    }
  },
});